package core

import (
	"strconv"
	"strings"

	"gitee.com/minph/fileScript/common"
)

// SkipNode 主执行器跳过区间块
func (n *Node) SkipNode() {
	children := seekNodes(n.ContextNode)

	for _, child := range children {
		child.Skip = true
	}

}

// RunChildren 执行子区间语句
func (n *Node) RunChildren(hook func(child *ContextNode)) {
	for _, child := range n.ContextNode.next {
		if hook != nil {
			hook(child)
		}
		child.Node.Run()
	}

}

// MatchCaller 匹配@标签
func (n *Node) MatchCaller(caller string) bool {
	return n.Caller == SentenceTag+caller
}

// GetCtx 在环境中查找参数
func GetCtx(callee string, context *ContextNode) interface{} {
	if common.IsStaticStr(callee) {
		return common.ToStaticStr(callee)
	}

	num, err := strconv.Atoi(callee)
	if err == nil {
		return num
	}

	double, err := strconv.ParseFloat(callee, 64)
	if err == nil {
		return double
	}

	flag, err := strconv.ParseBool(callee)
	if err == nil {
		return flag
	}

	index := strings.Index(callee, ".")

	if index == -1 {
		return nil
	}

	prefix := callee[:index]
	keyName := callee[index+1:]

	var ctx *ContextNode

	if prefix == "$" {
		ctx = context
	}

	if ctx == nil {
		return nil
	}

	for {
		if ctx.Vars[keyName] != nil {
			return ctx.Vars[keyName]
		}

		if ctx.prev == nil {
			return nil
		}
		ctx = ctx.prev
	}
}

// GetParamsList 获取多个列表参数
func GetParamsList(callee string, length int) []string {
	vars := strings.Split(callee, ",")

	if len(vars) != length {
		return nil
	}

	for i, v := range vars {
		vars[i] = strings.TrimSpace(v)
	}

	return vars
}

// Get2Params 获取两个参数
func Get2Params(callee string) []string {
	vars := make([]string, 2)
	index := strings.Index(callee, ",")

	if index == -1 {
		return nil
	}

	vars[0] = strings.TrimSpace(callee[:index])
	vars[1] = strings.TrimSpace(callee[index+1:])

	return vars
}

// SameNode 可认为是同一 Node
func SameNode(a *Node, b *Node) bool {
	if a.Callee == b.Callee && a.Caller == b.Caller && a.Line == b.Line {
		return true
	}

	return false
}
